import axios from 'axios'
import { ElMessage } from 'element-plus'

const request = axios.create({
  baseURL: '/api',
  timeout: 10000,
  headers: { 'Content-Type': 'application/x-www-form-urlencoded ;charset=UTF-8' },
})

// 请求拦截器

request.interceptors.request.use(
  (config) => {
    //在请求之前做些什么

    // const token = localStorage.getItem('token');//假设你将token放在localStorage中关机后还有
    const token = sessionStorage.getItem('token') //临时的
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }

    return config
  },
  (error) => {
    //对请求错误做些什么
    return Promise.reject(error)
  },
)

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    console.log('服务端响应', response)

    //对响应数据做些什么

    if (response.status === 200) {
      return request
    } else {
      return Promise.reject(response.data.data.msg || 'error')
    }
  },
  (error) => {
    //对响应错误做些什么

    let message = error.message || 'error'
    if (error.response) {
      switch (error.response.status) {
        case 400:
          message = '请求错误'
          break
        case 401:
          message = '未授权，请重新登录'

          break
        case 403:
          message = '拒绝访问'
          break
        case 404:
          message = '请求地址出错'
          break
        case 405:
          message = '不允许该请求方法'
          break
        case 408:
          message = '请求超时'
          break
        case 500:
          message = '服务器内部错误'
          break
        case 501:
          message = '服务未实现'
          break
        case 502:
          message = '网关错误'
          break
        case 503:
          message = '服务不可用'
          break
        case 504:
          message = '网关超时'
          break
        case 505:
          message = 'HTTP版本不受支持'
          break
        default:
          message = '网络异常'
          break
      }
      ElMessage.error({
        message: message,
        type: 'error',
        offset: 150,
        zIndex: 9999,
      })
      if (error.response.status === 401) {
        // // 清除token
        // sessionStorage.removeItem('token')
        console.log('12132131')

        // 跳转到登录页
        location.href = '/login'
      } else {
        return Promise.reject(message)
      }
    }
  },
)

export default request
